<script setup lang="ts">
import { Lock, User } from '@element-plus/icons-vue'
import type {
  FormInstance,
  InputInstance,
} from 'element-plus'
import { Logo } from './components'
import { foremRules, useHistoricalUsers } from './index'
import svg from '@/assets/images/login/login-preview.svg'
import { UserInfoEnum } from '@/enum'
// import Cookies from 'js-cookie';
import { sysUserApi } from '@/api'
// import * as sysUserApi from '@/api/modules/sysUser';
import { useUserStore } from '@/store'
import type { UserLoginParams } from '@/types'

const appName = import.meta.env.VITE_BASE_TITLE
const router = useRouter()
const { exclude } = useKeepPageStore()
exclude()
const { updateProjectVersion } = useServiceUpdate()
const [loginForm, setLoginForm] = useState<UserLoginParams>(
  {
    passWord: '',
    loginName: '',
  },
)

const isRemember = ref<boolean>(false)
const formRef = ref<FormInstance>()
const inputRef = ref<InputInstance>()

const { setUserInfo } = useUserStore()

const loginFormEncrypted = computed<UserLoginParams>(() => {
  const info = toValue(loginForm)
  return {
    loginName: info.loginName,
    passWord: cryptoEncryption(info.passWord),
  }
})
const { users, update } = useHistoricalUsers(
  isRemember,
  loginFormEncrypted,
)

function init() {
  inputRef.value?.focus?.()

  // 带出最近的一个账号信息
  const caches = toValue(users)
  const cache = caches[0]
  if (cache) {
    setLoginForm({
      loginName: cache.loginName,
      passWord: cryptoDecrypt(cache.passWord),
    })
  }

  isRemember.value = true
}

/** 登录 */
async function login() {
  const isValid = await formRef.value?.validate()
  if (!isValid)
    return

  // 调用登录接口
  const { data, code } = await sysUserApi.login(
    toValue(loginForm),
  )

  if (code !== 200 || !data)
    return
  // 保存 token 到 cookie
  // Cookies.set(UserInfoEnum.TOKEN, data?.tk ?? 'token', {
  //   expires: 7
  // });
  localStorage.setItem(UserInfoEnum.TOKEN, data?.tk ?? 'token')
  // 保存用户对象到 store
  setUserInfo(data)
  // 更新记住用户缓存列表
  update()

  // 更新项目hash
  updateProjectVersion()
  // 跳转到系统导航页面
  router.push('/system-navigation').catch(() => {})
}

onMounted(() => {
  init()
})
</script>

<template>
  <div
    class="width-fill height-fill align-center login login-page flex"
  >
    <div
      class="height-fill flex-incompressible login-left animate__animated animate__fast animate__slideInLeft width-4/7 relative"
    >
      <!-- 标题 -->
      <div
        class="align-center animate__animated login-left__title animate__delay-2s animate__fadeIn margin-top-xl margin-left-xl absolute flex gap-xs"
        style="--animate-delay: 0.4s"
      >
        <img
          src="@/assets/images/logo.png"
          alt=""
          srcset=""
        >
        <div>
          <p class="margin-0 fs-28">
            {{ appName }}
          </p>
          <p class="margin-0 fs-12">
            <span>监测</span>
            ·
            <span>双控</span>
            ·
            <span>能耗</span>
            ·
            <span>治理</span>
          </p>
        </div>
      </div>
      <!-- 中心 -->
      <Logo
        fluctuation="4"
        :svg="svg"
        class="animate__animated animate__delay-2s animate__fadeIn login-left__preview width-3/5 absolute"
        style="--animate-delay: 0.4s"
      />
      <!-- 右侧波浪 -->
      <img
        class="height-fill login-left__wave absolute"
        src="@/assets/images/login/login-bg.svg"
        alt=""
        srcset=""
      >
    </div>
    <div
      class="flex-fillRemaining height-fill login-right relative text-center"
    >
      <div
        class="padding-bottom-sm animate__animated animate__fast login-right__form animate__lightSpeedInRight padding-top-lg padding-lr box-border"
      >
        <h2
          class="animate__animated animate__delay-2s animate__fadeInUp margin-top-0 margin-bottom-lg"
          style="--animate-delay: 0.4s"
        >
          👋欢迎来到{{ appName }}👋
        </h2>
        <el-form
          ref="formRef"
          :model="loginForm"
          :rules="foremRules"
        >
          <el-form-item
            prop="loginName"
            class="animate__animated animate__delay-2s animate__fadeInUp"
            style="--animate-delay: 0.6s"
          >
            <el-input
              ref="inputRef"
              v-model="loginForm.loginName"
              :prefix-icon="User"
              placeholder="用户名"
              @keyup.enter="login"
            />
          </el-form-item>
          <el-form-item
            prop="passWord"
            class="animate__animated animate__delay-2s animate__fadeInUp"
            style="--animate-delay: 0.7s"
          >
            <el-input
              v-model="loginForm.passWord"
              show-password
              type="password"
              placeholder="密码"
              :prefix-icon="Lock"
              @keyup.enter="login"
            />
          </el-form-item>
          <el-form-item
            class="animate__animated animate__delay-2s animate__fadeInUp"
            style="--animate-delay: 0.8s"
          >
            <div
              class="width-fill align-center flex justify-between"
            >
              <el-checkbox
                v-model="isRemember"
                label="记住我"
                name="type"
              />
              <RouterLink v-if="false" to="/login">
                忘记密码了？
              </RouterLink>
            </div>
          </el-form-item>
          <el-form-item
            class="animate__animated animate__delay-2s animate__fadeInUp"
            style="--animate-delay: 0.9s"
          >
            <el-button
              type="primary"
              class="width-fill"
              @click="login"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
        <p
          v-if="false"
          class="fs-14 animate__animated animate__delay-2s animate__fadeInUp login-right__form-tip margin-bottom-0"
          style="--animate-delay: 1s"
        >
          还没有新账号？
          <RouterLink to="/login">
            创建新账号
          </RouterLink>
        </p>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login {
  --theme: #26a59a;
  --bgc-theme: #d3efff;
  --bgi-width: 100px;
  &-left {
    background-image: linear-gradient(
      to right,
      var(--bgc-theme),
      var(--bgc-theme) calc(100% - var(--bgi-width) + 10px),
      #fff calc(100% - var(--bgi-width) + 10px),
      #fff
    );
    &__title {
      top: 0;
      left: 0;
      color: var(--theme);
      img {
        width: 52px;
      }
      p:nth-of-type(2) {
        margin-top: 4px;
        letter-spacing: 0.24em;
      }
    }
    &__preview {
      z-index: 99;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      filter: drop-shadow(1px 1px 1px rgba(0, 0, 0, 0.4));
    }
    &__wave {
      top: 0;
      right: 0;
      width: var(--bgi-width);
    }
  }

  &-right {
    display: grid;
    place-content: center;
    transform-style: preserve-3d;
    h2 {
      color: var(--theme);
      opacity: 0.6;
      filter: drop-shadow(0 0 10px);
    }
    a {
      text-decoration: none;
      color: var(--theme);
    }
    &__form {
      width: 440px;
      // min-height: 600px;
      border-radius: 6px;
      background-color: #fff;
      box-shadow: 0 8px 32px #0000000d;
      transition: all 0.2s;
      &:hover {
        box-shadow: 0 8px 16px #0000001a;
      }
      &-tip {
        color: var(--el-text-color-disabled);
      }
    }
  }
}
//------------------组件样式------------------
//-------------样式穿透-------------
</style>
